package com.example.dell.fastshopping.user.ensureMoney;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.Trade.TradeExtraclActivity;
import com.example.dell.fastshopping.Trade.TradeRechargeActivity;
import com.example.dell.fastshopping.network.http.BaseResponse;
import com.example.dell.fastshopping.user.modle.EnsureMoneyActivityViewModel;
import com.example.dell.fastshopping.user.entity.UserInfo;
import com.example.dell.fastshopping.utils.ToastUtils;
import com.example.dell.fastshopping.views.BaseListActivity;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EnsureMoneyActivity extends BaseListActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.refresh)
    TwinklingRefreshLayout refresh;
    @BindView(R.id.my_ensure_money)
    TextView myEnsureMoney;
    @BindView(R.id.margin_rv)
    RecyclerView margin_rv;
    @BindView(R.id.nodata)
    LinearLayout nodata;
    private EnsureMoneyActivityViewModel model;
    private List<EnsureMoney> list;
    private List<UserInfo.Amounts> mMarginList;
    private int TRADE_EXTRACL_CODE = 102;
    private int TRADE_RECHARGE_CODE = 103;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ensure_money);
        ButterKnife.bind(this);
        super.initData();
        model = ViewModelProviders.of(this).get(EnsureMoneyActivityViewModel.class);
        initView();
    }


    @Override
    protected TwinklingRefreshLayout getRefreshLayout() {
        return refresh;
    }

    private void initView() {
        title.setText("保证金");
        margin_rv.setLayoutManager(new LinearLayoutManager(this));
        margin_rv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    }

    @Override
    protected void onResume() {
        super.onResume();
        getBaseData();
        getNetData(1, 10);
    }

    private void getBaseData() {
        model.getMyAllMoney().observe(this, new Observer<BaseResponse>() {
            @Override
            public void onChanged(@Nullable BaseResponse response) {
                //我所有的保证金
                //KLog.e(new GsonBuilder().create().toJson(response.getData()));
                BigDecimal bigDecimal = new BigDecimal(String.valueOf(response.getData()));
                myEnsureMoney.setText(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
            }
        });
        model.getMarginType().observe(this, new Observer<List<UserInfo.Amounts>>() {
            @Override
            public void onChanged(@Nullable List<UserInfo.Amounts> list) {
//                KLog.e(new GsonBuilder().create().toJson(response.getData()));
                //[{"id":1.0,"gradeName":"体验场"},{"id":2.0,"gradeName":"普通场"},{"id":3.0,"gradeName":"高级场"},{"id":4.0,"gradeName":"精英场"},{"id":5.0,"gradeName":"专家场"}]
                //保证金列表
                mMarginList = list;
                margin_rv.setAdapter(new MyMarginAdapter());

            }
        });
    }

    @Override
    protected void getNetData(final int page, int pageSize) {
        model.getMoneyHistory(page, pageSize).observe(this, new Observer<BaseResponse>() {
            @Override
            public void onChanged(@Nullable BaseResponse response) {
                Object data = response.getData();
                if (data instanceof LinkedTreeMap) {
                    LinkedTreeMap treeMap = (LinkedTreeMap) data;
                    String s = new GsonBuilder().enableComplexMapKeySerialization().create().toJson(treeMap);
                    EnsureMoney ensureMoney = new GsonBuilder().create().fromJson(s, EnsureMoney.class);
                    if (page == 1) {
                        list = ensureMoney.getList();
                    } else {
                        list.addAll(ensureMoney.getList());
                    }
                    if (list.size() == 0) {
                        nodata.setVisibility(View.VISIBLE);
                    } else {
                        nodata.setVisibility(View.GONE);
                    }
                    RecyclerView.Adapter adapter = rv.getAdapter();
                    if (adapter == null) {
                        rv.setAdapter(new MyAdapter());
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                    loadFinsh();
                } else {
                    ToastUtils.showShort("数据格式异常");
                }
            }
        });
    }

    @OnClick(R.id.back)
    public void onClick() {
        finish();
    }

    private class MyAdapter extends RecyclerView.Adapter<MyHolder> {
        @NonNull
        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View inflate = LayoutInflater.from(EnsureMoneyActivity.this).inflate(R.layout.item_ensure, viewGroup, false);
            return new MyHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull MyHolder myHolder, int i) {
            EnsureMoney ensureMoney = list.get(i);
            myHolder.ensure_type.setText(ensureMoney.getGradeName() + " " + ensureMoney.getTypenoString());
            myHolder.time.setText(ensureMoney.getPayTimeString());

            myHolder.e_money.setText(ensureMoney.getTypenoStatus() + ensureMoney.getMoneyString());
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
    }


    private class MyMarginAdapter extends RecyclerView.Adapter<MyHolder> {
        @NonNull
        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View inflate = LayoutInflater.from(EnsureMoneyActivity.this).inflate(R.layout.item_ensure_margin, viewGroup, false);
            return new MyHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull MyHolder viewHolder, int i) {
            UserInfo.Amounts amounts = mMarginList.get(i);
            viewHolder.title.setText(amounts.getGradeName());

            viewHolder.money.setText("￥" + amounts.getAmountString() + "/" + amounts.getVal());
            viewHolder.setMyMoney(amounts.getAmountString());

            int gray = EnsureMoneyActivity.this.getResources().getColor(R.color.myGrey);
            int red = EnsureMoneyActivity.this.getResources().getColor(R.color.myRed);
            viewHolder.pick_up.setOnClickListener(viewHolder);
            viewHolder.recharge.setOnClickListener(viewHolder);

            viewHolder.setGradId(amounts.getId());
            viewHolder.setMarginId(amounts.getMid());
            viewHolder.setGradName(amounts.getGradeName());

            if ("体验场".equals(amounts.getGradeName())) {
                viewHolder.money.setText("无");
                viewHolder.pick_up.setBackgroundResource(R.drawable.gray_circle_buttom);
                viewHolder.recharge.setBackgroundResource(R.drawable.grey_empty_circle_buttom);
                viewHolder.recharge.setTextColor(gray);
                viewHolder.recharge.setClickable(false);
                viewHolder.pick_up.setClickable(false);
            } else {
                viewHolder.pick_up.setBackgroundResource(R.drawable.red_button);
                viewHolder.recharge.setBackgroundResource(R.drawable.red_empty_buttom);
                viewHolder.recharge.setTextColor(red);
                viewHolder.recharge.setClickable(true);
                viewHolder.pick_up.setClickable(true);
            }

        }

        @Override
        public int getItemCount() {
            return mMarginList.size();
        }
    }

    private class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        //---------------MyMarginAdapter-----------
        public TextView title;
        public TextView money;
        public TextView recharge;
        public TextView pick_up;
        //--------------MyAdapter-------
        public TextView ensure_type;
        public TextView time;
        public TextView e_money;
        private int gradId;
        private int marginId;
        private String gradName;
        private String myMoney;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            money = itemView.findViewById(R.id.money);
            recharge = itemView.findViewById(R.id.recharge);
            pick_up = itemView.findViewById(R.id.pick_up);
            ensure_type = itemView.findViewById(R.id.ensure_type);
            time = itemView.findViewById(R.id.time);
            e_money = itemView.findViewById(R.id.e_money);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.pick_up:
                    toExtralActivty();
                    break;

                case R.id.recharge:
                    toChongzhiPage();
                    break;
            }
        }

        private void toExtralActivty() {
            //提现
            Intent intent = new Intent(EnsureMoneyActivity.this, TradeExtraclActivity.class);
            intent.putExtra("gradId", gradId);
            intent.putExtra("gradName", gradName);
            intent.putExtra("money", myMoney);
            intent.putExtra("from", "ensureMoney");
            EnsureMoneyActivity.this.startActivityForResult(intent, TRADE_EXTRACL_CODE);
        }

        private void toChongzhiPage() {
            //充值
            Intent intent = new Intent(EnsureMoneyActivity.this, TradeRechargeActivity.class);
            intent.putExtra("gradId", gradId);
            intent.putExtra("marginId", marginId);
            intent.putExtra("gradName", gradName);
            intent.putExtra("money", myMoney);
            intent.putExtra("from", "ensureMoney");
            EnsureMoneyActivity.this.startActivityForResult(intent, TRADE_RECHARGE_CODE);
        }

        public void setGradId(int id) {
            this.gradId = id;
        }

        public void setGradName(String gradeName) {
            this.gradName = gradeName;
        }

        public void setMyMoney(String amountString) {
            this.myMoney = amountString;
        }

        public void setMarginId(int mid) {
            this.marginId = mid;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
